// For help, see https://github.com/koajs/router
const fs = require('fs');
const path = require('path');
const cosService = require('../cosService');

module.exports = (router) => {
  // 数据文件路径
  const dataFilePath = path.join(__dirname, '../../public/project.json');

  // 初始化数据文件（从云端同步到本地）
  async function initializeDataFile() {
    try {
      // 如果本地文件不存在，尝试从云端下载
      if (!fs.existsSync(dataFilePath)) {
        console.log('本地文件不存在，尝试从云端下载初始数据...');
        const cloudData = await cosService.downloadData();
        if (cloudData) {
          // 确保目录存在
          const dir = path.dirname(dataFilePath);
          if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir, { recursive: true });
          }
          
          fs.writeFileSync(dataFilePath, JSON.stringify(cloudData, null, 2), 'utf8');
          console.log('云端数据已下载到本地');
          return cloudData;
        }
      }
    } catch (error) {
      console.error('初始化数据文件失败:', error);
    }
    return null;
  }

  // 读取数据文件（同步，仅从本地读取）
  function readDataFile() {
    try {
      if (fs.existsSync(dataFilePath)) {
        const data = fs.readFileSync(dataFilePath, 'utf8');
        const localData = JSON.parse(data);
        return localData;
      }
    } catch (error) {
      console.error('读取本地数据文件失败:', error);
    }
    
    // 返回默认数据结构，包含默认分组：产品组和前端组
    return { 
      projectGroups: [
        {
          id: 'group-product',
          name: '产品组',
          createdAt: new Date(),
          updatedAt: new Date()
        },
        {
          id: 'group-frontend',
          name: '前端组',
          createdAt: new Date(),
          updatedAt: new Date()
        }
      ], 
      projects: [] 
    };
  }

  // 写入数据文件（本地+云端同步）
  function writeDataFile(data) {
    try {
      // 先写入本地文件
      fs.writeFileSync(dataFilePath, JSON.stringify(data, null, 2), 'utf8');
      console.log('数据写入本地文件成功');
      
      // 异步同步到云端（不阻塞主流程）
      cosService.syncToCloud(data);
      
      return true;
    } catch (error) {
      console.error('写入数据文件失败:', error);
      return false;
    }
  }

  // CORS中间件
  router.use(async (ctx, next) => {
    // 设置CORS头部
    ctx.set('Access-Control-Allow-Origin', '*');
    ctx.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    ctx.set('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
    
    // 处理预检请求
    if (ctx.method === 'OPTIONS') {
      ctx.status = 200;
      return;
    }
    
    await next();
  });

  router.get('/cgi-bin/init', (ctx) => {
    ctx.body = 'Hello whistle111.';
  });

  // 获取所有项目
  router.get('/cgi-bin/api/project', (ctx) => {
    const data = readDataFile();
    ctx.body = {
      success: true,
      data: data.projects
    };
  });

  // 获取单个项目
  router.get('/cgi-bin/api/project/:id', (ctx) => {
    const data = readDataFile();
    const project = data.projects.find(p => p.id === ctx.params.id);
    if (!project) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '项目不存在'
      };
      return;
    }
    ctx.body = {
      success: true,
      data: project
    };
  });

  // 创建项目
  router.post('/cgi-bin/api/project', (ctx) => {
    const { name, description, groupId, environments } = ctx.request.body;
    
    if (!name) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '项目名称不能为空'
      };
      return;
    }

    const data = readDataFile();

    // 验证分组是否存在
    if (groupId && !data.projectGroups.find(g => g.id === groupId)) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '指定的项目分组不存在'
      };
      return;
    }

    const newProject = {
      id: generateUUID(),
      name,
      description: description || '',
      groupId: groupId || data.projectGroups[0]?.id || '',
      environments: (environments || []).map(env => ({
        id: generateUUID(),
        name: env.name,
        type: env.type,
        hosts: env.hosts || [],
        isActive: false
      })),
      createdAt: new Date(),
      updatedAt: new Date()
    };

    data.projects.push(newProject);
    
    if (writeDataFile(data)) {
      ctx.body = {
        success: true,
        data: newProject
      };
    } else {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '项目创建失败'
      };
    }
  });

  // 更新项目
  router.put('/cgi-bin/api/project/:id', (ctx) => {
    const data = readDataFile();
    const projectIndex = data.projects.findIndex(p => p.id === ctx.params.id);
    if (projectIndex === -1) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '项目不存在'
      };
      return;
    }

    const { name, description, groupId, environments } = ctx.request.body;
    
    // 验证分组是否存在
    if (groupId && !data.projectGroups.find(g => g.id === groupId)) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '指定的项目分组不存在'
      };
      return;
    }

    const updatedProject = {
      ...data.projects[projectIndex],
      name: name || data.projects[projectIndex].name,
      description: description !== undefined ? description : data.projects[projectIndex].description,
      groupId: groupId || data.projects[projectIndex].groupId,
      updatedAt: new Date()
    };

    if (environments) {
      updatedProject.environments = environments.map(env => ({
        id: env.id || generateUUID(),
        name: env.name,
        type: env.type,
        hosts: env.hosts || [],
        isActive: env.isActive || false
      }));
    }

    data.projects[projectIndex] = updatedProject;
    
    if (writeDataFile(data)) {
      ctx.body = {
        success: true,
        data: updatedProject
      };
    } else {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '项目更新失败'
      };
    }
  });

  // 删除项目
  router.delete('/cgi-bin/api/project/:id', (ctx) => {
    const data = readDataFile();
    const projectIndex = data.projects.findIndex(p => p.id === ctx.params.id);
    if (projectIndex === -1) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '项目不存在'
      };
      return;
    }

    data.projects.splice(projectIndex, 1);
    
    if (writeDataFile(data)) {
      ctx.body = {
        success: true,
        message: '项目删除成功'
      };
    } else {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '项目删除失败'
      };
    }
  });

  // ==================== 项目分组管理接口 ====================
  
  // 获取所有分组
  router.get('/cgi-bin/api/group', (ctx) => {
    const data = readDataFile();
    ctx.body = {
      success: true,
      data: data.projectGroups
    };
  });

  // 获取单个分组
  router.get('/cgi-bin/api/group/:id', (ctx) => {
    const data = readDataFile();
    const group = data.projectGroups.find(g => g.id === ctx.params.id);
    if (!group) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '分组不存在'
      };
      return;
    }
    ctx.body = {
      success: true,
      data: group
    };
  });

  // 创建分组
  router.post('/cgi-bin/api/group', (ctx) => {
    const { name } = ctx.request.body;
    
    if (!name) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '分组名称不能为空'
      };
      return;
    }

    const data = readDataFile();

    // 检查分组名称是否已存在
    if (data.projectGroups.find(g => g.name === name)) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '分组名称已存在'
      };
      return;
    }

    const newGroup = {
      id: generateUUID(),
      name,
      createdAt: new Date(),
      updatedAt: new Date()
    };

    data.projectGroups.push(newGroup);
    
    if (writeDataFile(data)) {
      ctx.body = {
        success: true,
        data: newGroup
      };
    } else {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '分组创建失败'
      };
    }
  });

  // 更新分组
  router.put('/cgi-bin/api/group/:id', (ctx) => {
    const data = readDataFile();
    const groupIndex = data.projectGroups.findIndex(g => g.id === ctx.params.id);
    if (groupIndex === -1) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '分组不存在'
      };
      return;
    }

    const { name } = ctx.request.body;
    
    // 检查分组名称是否已存在（排除当前分组）
    if (name && data.projectGroups.find(g => g.name === name && g.id !== ctx.params.id)) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '分组名称已存在'
      };
      return;
    }

    const updatedGroup = {
      ...data.projectGroups[groupIndex],
      name: name || data.projectGroups[groupIndex].name,
      updatedAt: new Date()
    };

    data.projectGroups[groupIndex] = updatedGroup;
    
    if (writeDataFile(data)) {
      ctx.body = {
        success: true,
        data: updatedGroup
      };
    } else {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '分组更新失败'
      };
    }
  });

  // 删除分组
  router.delete('/cgi-bin/api/group/:id', (ctx) => {
    const data = readDataFile();
    const groupIndex = data.projectGroups.findIndex(g => g.id === ctx.params.id);
    if (groupIndex === -1) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '分组不存在'
      };
      return;
    }

    // 检查是否有项目使用该分组
    const projectsInGroup = data.projects.filter(p => p.groupId === ctx.params.id);
    if (projectsInGroup.length > 0) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: `该分组下还有 ${projectsInGroup.length} 个项目，无法删除`
      };
      return;
    }

    data.projectGroups.splice(groupIndex, 1);
    
    if (writeDataFile(data)) {
      ctx.body = {
        success: true,
        message: '分组删除成功'
      };
    } else {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '分组删除失败'
      };
    }
  });

  // ==================== 云端同步状态接口 ====================
  
  // 检查云端连接状态
  router.get('/cgi-bin/api/cloud/status', async (ctx) => {
    try {
      const isConnected = await cosService.fileExists();
      const lastModified = isConnected ? await cosService.getLastModified() : null;
      
      ctx.body = {
        success: true,
        data: {
          connected: isConnected,
          lastModified: lastModified,
          localFileExists: fs.existsSync(dataFilePath)
        }
      };
    } catch (error) {
      ctx.body = {
        success: false,
        message: '检查云端状态失败',
        error: error.message
      };
    }
  });

  // 手动同步到云端
  router.post('/cgi-bin/api/cloud/sync', async (ctx) => {
    try {
      const data = readDataFile();
      const success = await cosService.uploadData(data);
      
      if (success) {
        ctx.body = {
          success: true,
          message: '数据已成功同步到云端'
        };
      } else {
        ctx.status = 500;
        ctx.body = {
          success: false,
          message: '同步到云端失败'
        };
      }
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '同步操作失败',
        error: error.message
      };
    }
  });

  // 从云端恢复数据
  router.post('/cgi-bin/api/cloud/restore', async (ctx) => {
    try {
      const cloudData = await cosService.downloadData();
      if (cloudData) {
        // 备份当前本地文件
        const backupPath = dataFilePath + '.backup.' + Date.now();
        if (fs.existsSync(dataFilePath)) {
          fs.copyFileSync(dataFilePath, backupPath);
        }

        // 写入云端数据到本地
        fs.writeFileSync(dataFilePath, JSON.stringify(cloudData, null, 2), 'utf8');
        
        ctx.body = {
          success: true,
          message: '数据已从云端恢复',
          backup: backupPath
        };
      } else {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '云端没有找到数据文件'
        };
      }
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '从云端恢复数据失败',
        error: error.message
      };
    }
  });

  // ==================== Whistle规则管理接口 ====================
  
  // 获取当前生成的whistle规则
  router.get('/cgi-bin/api/whistle/rules', (ctx) => {
    try {
      // 直接读取 rules.txt 文件内容
      const rulesFilePath = path.join(__dirname, '../../rules.txt');
      let rulesContent = '';
      
      if (fs.existsSync(rulesFilePath)) {
        rulesContent = fs.readFileSync(rulesFilePath, 'utf8');
      }
      
      // 从数据管理器获取环境信息
      const data = readDataFile();
      const activeEnvs = [];
      data.projects.forEach(project => {
        project.environments.forEach(env => {
          if (env.isActive) {
            activeEnvs.push({
              projectId: project.id,
              projectName: project.name,
              envId: env.id,
              envName: env.name,
              envType: env.type,
              hosts: env.hosts
            });
          }
        });
      });
      
      ctx.body = {
        success: true,
        data: {
          rulesContent: rulesContent,
          activeEnvironments: activeEnvs,
          rulesFilePath: rulesFilePath,
          rulesUpdated: true
        }
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取whistle规则失败',
        error: error.message
      };
    }
  });

  // 重新加载所有规则 (实时同步优化版)
  router.post('/cgi-bin/api/whistle/reload', async (ctx) => {
    try {
      const startTime = Date.now();
      
      // 直接更新 rules.txt 文件
      await updateRulesFile();
      
      const responseTime = Date.now() - startTime;
      
      // 设置无缓存响应头
      ctx.set('Cache-Control', 'no-cache, no-store, must-revalidate');
      ctx.set('Pragma', 'no-cache');
      ctx.set('Expires', '0');
      
      ctx.body = {
        success: true,
        message: '规则已实时更新，立即生效',
        data: {
          rulesUpdated: true,
          timestamp: new Date().toISOString(),
          responseTime: responseTime,
          forceRefresh: true
        }
      };
      
      console.log(`[NoHost] 规则重新加载完成 (${responseTime}ms)`);
      
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '更新规则文件失败',
        error: error.message
      };
    }
  });

  // 强制刷新规则 (新增接口，用于立即同步)
  router.post('/cgi-bin/api/whistle/force-refresh', async (ctx) => {
    try {
      const startTime = Date.now();
      
      // 读取当前数据并重新生成规则
      const data = readDataFile();
      const activeEnvs = [];
      
      data.projects.forEach(project => {
        project.environments.forEach(env => {
          if (env.isActive) {
            activeEnvs.push({
              projectId: project.id,
              projectName: env.name,
              envId: env.id,
              envName: env.name,
              envType: env.type,
              hosts: env.hosts
            });
          }
        });
      });
      
      // 立即更新 rules.txt 文件
      await updateRulesFile();
      
      // 强制刷新 Whistle 规则 (通过修改文件时间戳触发)
      await forceWhistleReload();
      
      const responseTime = Date.now() - startTime;
      
      // 设置强制无缓存响应头
      ctx.set('Cache-Control', 'no-cache, no-store, must-revalidate');
      ctx.set('Pragma', 'no-cache');
      ctx.set('Expires', '0');
      ctx.set('X-Force-Refresh', 'true');
      
      ctx.body = {
        success: true,
        message: '规则强制刷新成功，立即生效',
        data: {
          activeEnvironments: activeEnvs,
          rulesUpdated: true,
          timestamp: new Date().toISOString(),
          responseTime: responseTime,
          forceRefresh: true
        }
      };
      
      console.log(`[NoHost] 规则强制刷新完成 (${responseTime}ms)，激活环境数量: ${activeEnvs.length}`);
      
    } catch (error) {
      console.error('[NoHost] 强制刷新规则失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '强制刷新规则失败',
        error: error.message
      };
    }
  });

  // 强制 Whistle 重新加载规则
  async function forceWhistleReload() {
    try {
      const rulesFilePath = path.join(__dirname, '../../rules.txt');
      
      if (fs.existsSync(rulesFilePath)) {
        // 方法1: 修改文件时间戳，触发 Whistle 文件监控
        const stats = fs.statSync(rulesFilePath);
        const newTime = new Date();
        
        // 更新文件的访问时间和修改时间
        fs.utimesSync(rulesFilePath, newTime, newTime);
        
        console.log('[NoHost] 已更新 rules.txt 文件时间戳，触发 Whistle 重新加载');
      }
      
      // 方法2: 创建一个临时文件然后删除，强制触发文件系统事件
      const tempFilePath = path.join(__dirname, '../../.temp_trigger');
      fs.writeFileSync(tempFilePath, Date.now().toString());
      fs.unlinkSync(tempFilePath);
      
      console.log('[NoHost] 已创建临时触发文件，强制触发 Whistle 文件监控');
      
      // 方法3: 强制重写文件内容，确保文件系统事件被触发
      if (fs.existsSync(rulesFilePath)) {
        const content = fs.readFileSync(rulesFilePath, 'utf8');
        // 添加一个时间戳注释，然后重写文件
        const newContent = content + `\n# Last updated: ${new Date().toISOString()}`;
        fs.writeFileSync(rulesFilePath, newContent, 'utf8');
        
        // 立即恢复原内容
        fs.writeFileSync(rulesFilePath, content, 'utf8');
        
        console.log('[NoHost] 已强制重写 rules.txt 文件，确保文件系统事件被触发');
      }
      
    } catch (error) {
      console.warn('[NoHost] 强制刷新 Whistle 规则失败:', error);
      // 不影响主流程
    }
  }

  // 更新 rules.txt 文件的函数
  async function updateRulesFile() {
    try {
      const rulesFilePath = path.join(__dirname, '../../rules.txt');
      const data = readDataFile();
      
      // 构建规则内容
      let rulesContent = [
        '# 这个文件会被 whistle 自动加载为全局规则',
        '# 此处添加的规则会在 whistle 启动时自动生效',
        '# 优先级低于界面中的规则',
        '',
        '# 添加调试头部，用于验证插件加载成功',
        '* reqHeaders://x-whistle-nohost-plugin=loaded',
        '',
        '# === NoHost Plugin Active Environments ===',
        `# Generated at: ${new Date().toISOString()}`,
        ''
      ];
      
      // 添加激活环境的规则
      let hasActiveEnvs = false;
      data.projects.forEach(project => {
        project.environments.forEach(env => {
          if (env.isActive && env.hosts && env.hosts.length > 0) {
            hasActiveEnvs = true;
            rulesContent.push('');
            rulesContent.push(`# === Project: ${project.name} ===`);
            rulesContent.push(`# Environment: ${env.name} (${env.type})`);
            rulesContent.push(`# Project ID: ${project.id}`);
            rulesContent.push(`# Environment ID: ${env.id}`);
            rulesContent.push('');
            
            // 添加 host 规则
            env.hosts.forEach(hostConfig => {
              if (hostConfig && hostConfig.trim()) {
                const parts = hostConfig.trim().split(/\s+/);
                if (parts.length >= 2) {
                  const proxy = parts[0];    // 127.0.0.1:8181
                  const domain = parts[1];   // dgvip360.drivergenius3.com
                  const rule = `${domain} ${proxy}`;
                  rulesContent.push(rule);
                }
              }
            });
            
            // 添加调试头
            rulesContent.push(`* reqHeaders://x-nohost-active-env=${project.name}-${env.name}`);
            rulesContent.push('');
          }
        });
      });
      
      if (!hasActiveEnvs) {
        rulesContent.push('# No active environments');
        rulesContent.push('');
      }
      
      // 写入文件
      fs.writeFileSync(rulesFilePath, rulesContent.join('\n'), 'utf8');
      console.log('[NoHost] rules.txt 文件已更新');
      
      return true;
    } catch (error) {
      console.error('[NoHost] 更新 rules.txt 文件失败:', error);
      throw error;
    }
  }

  // ==================== 环境激活接口 ====================
  
  // 激活环境 (实时同步优化版)
  router.post('/cgi-bin/api/project/:id/environment/:envId/activate', async (ctx) => {
    const startTime = Date.now();
    const data = readDataFile();
    const project = data.projects.find(p => p.id === ctx.params.id);
    
    if (!project) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '项目不存在'
      };
      return;
    }

    const environment = project.environments.find(env => env.id === ctx.params.envId);
    if (!environment) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '环境不存在'
      };
      return;
    }

    // 标准环境类型
    const standardTypes = ['development', 'test', 'preview', 'production'];
    
    // 如果是标准环境，需要先关闭其他标准环境
    if (standardTypes.includes(environment.type)) {
      project.environments.forEach(env => {
        if (standardTypes.includes(env.type) && env.id !== ctx.params.envId) {
          env.isActive = false;
        }
      });
    }

    // 激活目标环境
    environment.isActive = true;

    if (writeDataFile(data)) {
      try {
        // 同时更新 rules.txt 文件 (备用)
        await updateRulesFile();
        
        // 强制刷新 Whistle 规则，确保立即生效
        await forceWhistleReload();
        
        const responseTime = Date.now() - startTime;
        
        // 设置无缓存响应头，确保前端获取最新数据
        ctx.set('Cache-Control', 'no-cache, no-store, must-revalidate');
        ctx.set('Pragma', 'no-cache');
        ctx.set('Expires', '0');
        
        ctx.body = {
          success: true,
          message: '环境激活成功，规则已实时更新',
          data: {
            environment: environment,
            rulesUpdated: true,
            timestamp: new Date().toISOString(),
            responseTime: responseTime,
            activeHosts: environment.hosts,
            // 为前端提供强制刷新的标识
            forceRefresh: true
          }
        };
        
        // 输出日志用于调试
        console.log(`[NoHost] 环境激活成功 (${responseTime}ms): ${project.name} - ${environment.name}`);
        console.log(`[NoHost] 激活的Host规则:`, environment.hosts);
        
      } catch (ruleError) {
        console.error(`[NoHost] 更新规则文件失败:`, ruleError);
        ctx.body = {
          success: true,
          message: '环境激活成功，但备用规则文件更新失败',
          data: {
            environment: environment,
            error: ruleError.message,
            timestamp: new Date().toISOString()
          }
        };
      }
    } else {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '环境激活失败'
      };
    }
  });

  // 取消激活环境 (实时同步优化版)
  router.post('/cgi-bin/api/project/:id/environment/:envId/deactivate', async (ctx) => {
    const startTime = Date.now();
    const data = readDataFile();
    const project = data.projects.find(p => p.id === ctx.params.id);
    
    if (!project) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '项目不存在'
      };
      return;
    }

    const environment = project.environments.find(env => env.id === ctx.params.envId);
    if (!environment) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '环境不存在'
      };
      return;
    }

    // 取消激活环境
    environment.isActive = false;

    if (writeDataFile(data)) {
      try {
        // 同时更新 rules.txt 文件 (备用)
        await updateRulesFile();
        
        // 强制刷新 Whistle 规则，确保立即生效
        await forceWhistleReload();
        
        const responseTime = Date.now() - startTime;
        
        // 设置无缓存响应头，确保前端获取最新数据
        ctx.set('Cache-Control', 'no-cache, no-store, must-revalidate');
        ctx.set('Pragma', 'no-cache');
        ctx.set('Expires', '0');
        
        ctx.body = {
          success: true,
          message: '环境取消激活成功，规则已实时更新',
          data: {
            environment: environment,
            rulesUpdated: true,
            timestamp: new Date().toISOString(),
            responseTime: responseTime,
            deactivatedHosts: environment.hosts,
            // 为前端提供强制刷新的标识
            forceRefresh: true
          }
        };
        
        // 输出日志用于调试
        console.log(`[NoHost] 环境取消激活成功 (${responseTime}ms): ${project.name} - ${environment.name}`);
        console.log(`[NoHost] 取消激活的Host规则:`, environment.hosts);
        
      } catch (ruleError) {
        console.error(`[NoHost] 更新规则文件失败:`, ruleError);
        ctx.body = {
          success: true,
          message: '环境取消激活成功，但备用规则文件更新失败',
          data: {
            environment: environment,
            error: ruleError.message,
            timestamp: new Date().toISOString()
          }
        };
      }
    } else {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '环境取消激活失败'
      };
    }
  });

  // UUID生成函数
  function generateUUID() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      const r = Math.random() * 16 | 0;
      const v = c === 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  }

  // 初始化数据文件（异步执行，不阻塞启动）
  setImmediate(async () => {
    try {
      await initializeDataFile();
      console.log('数据文件初始化完成');
    } catch (error) {
      console.error('数据文件初始化失败:', error);
    }
  });
};
